package com.gzdh.dishrecognition.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.EditText;
import android.widget.Toast;

import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.gzdh.dishrecognition.MainActivity;
import com.gzdh.dishrecognition.R;
import com.gzdh.dishrecognition.config.SysConstConfig;
import com.gzdh.dishrecognition.ui.base.BaseMVCActivity;
import com.gzdh.dishrecognition.util.SystemUtils;

public class LoginActivity extends BaseMVCActivity {
    private Context mContext;
    private EditText login_username;
    private EditText login_password;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        mContext = this;
        login_username = findViewById(R.id.login_username);
        login_password = findViewById(R.id.login_password);
    }

    @Override
    protected void initData() {
        SharedPreferences sharedPreferences = getSharedPreferences("systemI", Context.MODE_PRIVATE); //私有数据
        SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
        findViewById(R.id.btn_login).setOnClickListener(view -> {
            String user = login_username.getText().toString();
            String pass = login_password.getText().toString();
            if ("".equals(user) || "".equals(pass)) {
                Toast.makeText(mContext, "请输入信息", Toast.LENGTH_LONG).show();
                return;
            }

            RequestUtils.login(mContext, user, pass, SystemUtils.getSerialNumber(),
                    new MyObserverRes<>(mContext) {
                        @Override
                        public void onSuccess(String result) {
                            String[] array = result.split("-");
                            Toast.makeText(mContext, "登录成功", Toast.LENGTH_LONG).show();
                            editor.putString("user", user);
                            editor.putString("username", array[0]);
                            editor.putString("role", array[1]);
                            editor.putString("addressNo", array[2]);
                            editor.apply();
                            SysConstConfig.getInstance().setUser(user);
                            startActivity(new Intent(mContext, MainActivity.class));
                            finish();
                        }

                        @Override
                        public void onFailure(Throwable e, String errorMsg) {
                            Toast.makeText(mContext, errorMsg, Toast.LENGTH_LONG).show();
                            login_username.setText("");
                            login_password.setText("");
                        }
                    });
        });
    }

    @Override
    protected void dissmissPresnetation() {

    }
}
